/**打印类
 * 解决问题：　
 *  1.表格上信息可显示多个，超出３个排到第二行
 *  2.每个表格显示行数目可调控
 *  3.多表同时打印
 * 
 * 是否分联,比如3联就重复打印3张
 * 是否分页
 * 每页展示多少行数据
 * 每页表头一行展示多少行数据
 * 错误处理
 * 单据每一部分都是单独的一个函数，方便重写实现多态
 * set,get设置属性
 * @param {*} type 需要打印的单据类型
 * @param {*} bills 需要打印的单据id, 以分号隔开. 例如 5694;5968;8652;
 */
function Print(type, bills) {
    this.typeMap = {};      //每一种单据需要展示的信息的键值对
    this.billsData = {};     //具体数据
    this.RemoteDetailAddress = "http://222.196.35.4:8088/GSMS/logistics/";
    this.RemoteTypeAddress = "https://www.easy-mock.com/mock/5a4d84bee5f9cd651a7fbce4/GSMSprinttest/";
    this.buildUrlandCallIt(type, bills);
}
/**
 * 表头每一行的列数
 */
Print.prototype.tableTopInLineSize = 3; 
/**
 * 拼接url字符串地址,并获取数据
 * @param {*} type 需要打印的单据类型
 * @param {*} bills 需要打印的单据id, 以分号隔开. 例如 5694;5968;8652;
 */
Print.prototype.buildUrlandCallIt =  function (type, bills) {
    var typeUrl = this.RemoteTypeAddress + type;
    var dataUrl = this.RemoteDetailAddress + pageType +'/getborder.do?IDS=' + bills;
    this.loadRemote(typeUrl, 'typeMap');
    this.loadRemote(dataUrl, 'billsData');
}

/**后台获取数据
 * @param remote_data_url  url地址
 * @param remote_data_url  获取数据后要填充的对象
 */
Print.prototype.loadRemote = function(remote_data_url, obj) {
    var me = this;
    var xmlhttp;
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            me.buildMap(JSON.parse(xmlhttp.responseText), obj);
        }
    }
    xmlhttp.open("GET", remote_data_url, false);
    xmlhttp.send();
}

/**
 * 构建文字与数据的键值对
 * 进入函数后检查是否需要的两个数据都收到了,收到了进一步将表示类型的数据转换为方便使用的键值对
 * @param data 后台数据
 * @param obj  数据填充的对象
 */
Print.prototype.buildMap = function(data, obj) {
    this[obj] = data;
    if(JSON.stringify(this.typeData) != '{}' 
        && JSON.stringify(this.billsData) != '{}') 
    {
        for(var i in this.typeMap) {
            if(! this.typeMap[i].fieldname) {
                for(var j in this.typeMap[i]){
                    this.typeMap[j] = this.typeMap[i][j];
                }
                delete this.typeMap[i];
            }
        }
        console.log(this.typeMap);
        console.log(this.billsData);
        this.creatHTML();   //开始拼接字符串
    }
}

/**
 * 拼接字符串，构建整个单据
 */
Print.prototype.creatHTML = function() {
    if(! this.typeMap.maxRows){
        throw "Require a 'maxRows' in remote style-control data"
    }
    //将表格数据中按照位置分为三部分
    var tableTop = {};
    var tableBody = {};
    var tableBottom = {};   
    var printDetailArr = [];//表格中个列顺序
    for(var tableItem in this.typeMap) {
        switch(this.typeMap[tableItem].showposition)
        {
            case 'top' : tableTop[this.typeMap[tableItem].fieldname] = this.typeMap[tableItem].valuename; break;
            case 'body' : 
                tableBody[this.typeMap[tableItem].fieldname] = this.typeMap[tableItem].valuename; 
                printDetailArr.push(this.typeMap[tableItem].fieldname); 
                break;
            case 'bottom' : tableBottom[this.typeMap[tableItem].fieldname] = this.typeMap[tableItem].valuename; break;
        }
    }

    var htmlStr = "";
    for(var bill in this.billsData) {      //遍历需要打印的单据
        //每个订单需要分为多少页
        var PageLength = Math.ceil(this.billsData[bill].rows.length / this.typeMap.maxRows);
        
        var tableline = 0;  //每一页需要打印多少行;
        var sumPrice = 0;
        var sumAMOUNT = 0;
        
        //生成每一页
        for(var page = 0; page < PageLength; page++) {
            if (page == PageLength - 1) {
                htmlStr += "<div style='clear: both;' class='onePage PageNext'>";
            } else {
                htmlStr += "<div style='clear: both;'>";
            }
            //生成标题
            htmlStr += "<h1 align = 'center' style='margin: 0;'>" + this.typeMap.title + "</h1>";
            //生成表格头部
            htmlStr += "<table cellspacing = '6' style='margin-top: 0px;'>"
            var tempTableTopInLineSize = this.tableTopInLineSize;
            htmlStr += "<tr>";
            for(var tableTopItem in tableTop) {
                tempTableTopInLineSize--;
                htmlStr += "<th> " + tableTop[tableTopItem] + "</th>";
                htmlStr += "<td> " + this.billsData[bill][tableTopItem] + "</td>";
                if(tempTableTopInLineSize == 0) {
                    htmlStr += "</tr> <tr>"
                }
            }
            htmlStr += "</tr> </table>"
            //生成表格主体
            htmlStr += "<table style = 'margin-top: 0px; line-height:4px; border-collapse:collapse; ' border='1'>"
            htmlStr += "<tr>";
            //thead
            htmlStr += "<th>序号</th>"
            for(var tableBodyItem in tableBody) {
                htmlStr += "<th>" + tableBody[tableBodyItem] + "</th>"
            }
            var tableRows = this.billsData[bill].rows;

            //tbody
            for(var line = 0; line < this.typeMap.maxRows; line++) {
                htmlStr += "<tr>";
                htmlStr += "<td>" + (tableline + 1) + "</td>";
                for(var td = 0; td < printDetailArr.length; td++) {
                    var tdContent = tableRows[line + page*6][printDetailArr[td]];
                    htmlStr += "<td>" + tdContent + "</td>";
                    switch(printDetailArr[td])
                    {
                        case "AMOUNT" : sumAMOUNT += tdContent; break;
                        case "SUM" :  sumPrice += tdContent; break;
                    }
                }
                htmlStr += "</tr>";
                //合计栏
                tableline++;
                if(tableline == tableRows.length) {
                    htmlStr += "<td>合计</td>";
                    for(var td = 0; td < printDetailArr.length; td++) {
                        var sum;
                        switch(printDetailArr[td])
                        {
                            case "AMOUNT" : sum = sumAMOUNT; break;
                            case "SUM" : sum = sumPrice; break;
                            default: sum = "";
                        }
                        sum = parseFloat(sum).toFixed(1);
                        sum = sum =='NaN' ? "" : sum;
                        htmlStr += "<td>" + sum + "</td>";
                    }
                    break;
                }
            }
            htmlStr += "</table>";
            //表格尾部
            htmlStr += "<div style='width:100%;>" ;
            for(var tableBottomItem in tableBottom) {
                if(tableBottomItem == 'MEMO') {
                    htmlStr += "<div> <div style='width:20%;'>备注</div>";
                    htmlStr += "<div style='width:80%;'>" + this.billsData[bill].MEMO + "</div> </div>";
                }
                else {
                    htmlStr += "<div style='width:70px; float: left'>" 
                            + tableBottom[tableBottomItem] 
                            + ":</div> <div style='width:170px; float: left; border: 1px solid white;'>"
                            + (this.billsData[bill][tableBottomItem] == undefined ?  " " :  this.billsData[bill][tableBottomItem])
                            + "</div>";
                }
            }
            htmlStr += "<div style='width:30%; float: right;'>第" + (page+1) + "页 共" + PageLength +"页 </div>";
            htmlStr += "</div>";
            htmlStr += "</div>"
        }
    }
    document.getElementById('printContent').innerHTML = htmlStr;
}
